#include "RingQueue.hpp"
#include "Task.hpp"

// 生产者
void *Productor(void* args)
{
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);

    while (true)
    {
        int data1 = rand() % 10; // [1, 10] // 将来深刻理解生产消费，就要从这里入手，TODO
        usleep(rand() % 123);
        int data2 = rand() % 10; // [1, 10] // 将来深刻理解生产消费，就要从这里入手，TODO
        usleep(rand() % 123);
        char oper = opers[rand() % (opers.size())];
        Task t(data1, data2, oper);
        std::cout << "productor task: " << t.PrintTask() << std::endl;
        rq->push(t);
        
    }
}
// 消费者
void *Consumer(void* args)
{
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);
    while (true)
    {
        Task data ;
        rq->pop(&data);
        data();
        std::cout << "consumer done, data is : " << data.PrintResult() << std::endl;
        
        sleep(1);
    }
}
int main()
{
    pthread_t p[3],c[2];  // p生产者的线程ID, c消费者的线程ID
    RingQueue<Task> *rq = new RingQueue<Task>();
    // 线程创建
    pthread_create(&p[0], nullptr, Productor, rq);
    pthread_create(&p[1], nullptr, Productor, rq);
    pthread_create(&c[0], nullptr, Consumer, rq);
    pthread_create(&c[1], nullptr, Consumer, rq);
    pthread_create(&c[2], nullptr, Consumer, rq);

    // 线程等待
    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);
    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(c[2], nullptr);

    return 0;
}